<template>
  <div class="settings-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!--面包屑-->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-col :span="15">
        <el-form ref="settings-form" :rules="settingsRules" :model="user" label-width="80px">
          <el-form-item label="编号">
            {{ user.id }}
          </el-form-item>
          <el-form-item label="手机">
            {{ user.mobile }}
          </el-form-item>
          <el-form-item prop="name" label="媒体名称">
            <el-input v-model="user.name"></el-input>
          </el-form-item>
          <el-form-item prop="intro" label="媒体内容">
            <el-input type="textarea" v-model="user.intro"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onUpdateUser">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :offset="2" :span="4">
        <div>
          <label for="file">
            <el-avatar
              shape="square"
              :size="150"
              fit="cover"
              :src="user.photo"
            ></el-avatar>
            <p>点击修改头像</p>
          </label>
          <input
            id="file"
            type="file"
            hidden
            ref="file"
            @change="onFileChange"
          />
        </div>
      </el-col>
    </el-card>
    <!--弹出层-->
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      @opened="onDialogOpened"
      @closed="onDialogClosed"
    >
      <div class="preview-image-wrap">
        <img
          class="preview-image"
          ref="preview-image"
          :src="previewImage"
        >
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button
      type="primary"
      @click="onUpdatePhoto"
    >确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/api/user'
import globalBus from '@/utils/global-bus'

import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
  name: 'SettingsIndex',
  components: {},
  props: {},
  data () {
    return {
      // 用户资料
      user: {
        id: null,
        name: '',
        mobile: '',
        email: '',
        intro: '',
        photo: ''
      },
      settingsRules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'change'
          }
        ],
        intro: [
          {
            required: true,
            message: '请输入简介',
            trigger: 'change'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'change'
          }
        ]
      },
      dialogVisible: false, // 控制图片上传裁切预览的显示状态
      previewImage: '', // 上传头像预览
      cropper: null, // 头像裁切器实例
      updateProfileLoading: false, // 修改用户资料时的 loading 状态
      updatePhotoLoading: false
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadUser()
  },
  mounted () {
  },
  methods: {
    onFileChange () {
      this.dialogVisible = true
      const file = this.$refs.file
      const blobData = window.URL.createObjectURL(file.files[0])
      this.previewImage = blobData

      // 解决多次选择同一个文件不触发change事件问题
      this.$refs.file.value = ''
    },
    onUpdateUser () {
      // 表单验证，验证通过，提交表单
      this.$refs['settings-form'].validate(valid => {
        if (!valid) {
          return
        }
        // 开启 loading 状态
        this.updateProfileLoading = true
        const {
          name,
          intro,
          email
        } = this.user
        updateUserProfile({
          name,
          intro,
          email
        }).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功'
          })

          // 关闭 loading 状态
          this.updateProfileLoading = false

          // 发布通知，用户信息已修改
          globalBus.$emit('update-user', this.user)
        })
      })
    },
    // 获取用户资料
    loadUser () {
      getUserProfile().then(res => {
        this.user = res.data.data
      })
    },
    onDialogOpened () {
      // 图片裁切器必须基于img进行初始化
      // 注意：img 必须是可见状态才能正常完成初始化
      // 获取图片 DOM 节点
      const image = this.$refs['preview-image']
      // 如果预览图发生变化需要更新裁切器:
      // 方式一：裁切器.replace 方法
      // 方式二：销毁裁切器，重新初始化
      // 初始化裁切器
      if (this.cropper) {
        // 使用replace的方式要比destroy方式更节省资源
        this.cropper.replace(this.previewImage)
        return
      }
      this.cropper = new Cropper(image, {
        viewMode: 1,
        dragMode: 'none',
        aspectRatio: 1,
        cropBoxMovable: true,
        cropBoxResizable: true,
        background: true,
        movable: true
        // crop (event) {
        //   console.log(event.detail.x)
        //   console.log(event.detail.y)
        //   console.log(event.detail.width)
        //   console.log(event.detail.height)
        //   console.log(event.detail.rotate)
        //   console.log(event.detail.scaleX)
        //   console.log(event.detail.scaleY)
        // }
      })
    },

    onDialogClosed () {
      // 对话框关闭，销毁裁切器
      // this.cropper.destroy()
    },
    // 更新用户头像
    onUpdatePhoto () {
      // 让确定按钮开始 loading
      this.updatePhotoLoading = true
      // 获取裁切的图片对象
      this.cropper.getCroppedCanvas().toBlob(file => {
        const fd = new FormData()
        fd.append('photo', file)
        // 提交请求 fd
        updateUserPhoto(fd).then(res => {
          console.log(res)
          // 关闭对话框
          this.dialogVisible = false
          // 更新视图展示

          // 直接把裁切结果的文件对象转为 blob数据本地预览
          this.user.photo = window.URL.createObjectURL(file)

          // 关闭确定按钮的 loading
          this.updatePhotoLoading = false

          this.$message({
            type: 'success',
            message: '更新头像成功'
          })

          globalBus.$emit('update-user', this.user)

          // 把服务端返回的图片进行展示有点慢
          // this.user.photo = res.data.data
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
.preview-image-wrap {
  /* Ensure the size of the image fit the container perfectly */

  .preview-image {
    display: block;

    /* This rule is very important, please don't ignore this */
    max-width: 100%;
    height: 200px;
  }
}
</style>
